import { ArgumentMetadata, BadRequestException, HttpException, HttpStatus, Injectable, PipeTransform } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { validate, ValidationError } from "class-validator";

@Injectable()
export class UserPipeValidate implements PipeTransform {
  async transform(value: any, metadata: ArgumentMetadata) {
    const dto = plainToInstance(metadata.metatype, value);
    const errInfo: ValidationError[] = await validate(dto)
    if (errInfo.length > 0) {
      // console.log('错误信息',errInfo)
      throw process.env.NODE_ENV ? new HttpException(errInfo, HttpStatus.BAD_REQUEST)
        : new BadRequestException(JSON.stringify(errInfo.shift().constraints));
    }
    return value;
  }
}
